import {Body, Controller, Get, HttpStatus, Post, Query, Req, Res} from '@nestjs/common';
import {Response} from 'express';
import {CommonRedisService} from '../../service/common.redis.service';
import {CommonResponseDto} from '../../dto/common.response.dto';
import {ResCode} from '../../common/constants';
import {uuid} from '../../common/utils';
import AppConfig from 'config/app.config';
import {CommonRequestService} from "../../service/common.request.service";
import {getAccessToken, getDingDingHeaders} from "../../common/common";


@Controller('ding-auth')
export class AuthController{
    constructor(private readonly commonRedisService: CommonRedisService, private readonly commonRequestService: CommonRequestService) {

    }

    @Post('/gettoken')
    async getToken(@Res({ passthrough: true }) res: Response) {
        res.status(HttpStatus.OK);
        const token = await getAccessToken(this.commonRedisService, this.commonRequestService)
        if (token) {
            return new CommonResponseDto(ResCode.OK, '成功', {accessToken: token})
        } else {
            return new CommonResponseDto(ResCode.ERROR, '服务异常', null)
        }
    }
    @Post('/getuser')
    async getUserInfo(@Body() body: {authCode: string}, @Res({ passthrough: true }) res: Response) {
        res.status(HttpStatus.OK);
        if (!body.authCode) {
            return new CommonResponseDto(ResCode.ERROR, 'authCode参数缺失', null)
        }
        const token = await getAccessToken(this.commonRedisService, this.commonRequestService)
        const query = {
            access_token: token,
            auth_code: body.authCode || ''
        }
        console.log('getUserInfo query', query)
        if (token) {
            try {
                const api = '/rpc/oauth2/dingtalk_app_user.json'
                const headers = getDingDingHeaders('get', api, query)
                const result = await this.commonRequestService.get(`${AppConfig.DingDing.Domain}${api}`, {
                    headers,
                    params: query
                })
                if (result.content && result.content.data) {
                    let miniToken = await this.commonRedisService.get(AppConfig.DingDing.MiniProgramTokenKey)
                    if (!miniToken) {
                        miniToken = uuid(32)
                        this.commonRedisService.set(AppConfig.DingDing.MiniProgramTokenKey, miniToken, 604800)
                    }
                    console.log('getUserInfo success', result.content.data)
                    return new CommonResponseDto(ResCode.OK, '成功', {...result.content.data, ...{miniToken}})
                }
                console.log('getUserInfo fail', result)
                return new CommonResponseDto(ResCode.ERROR, '获取用户信息失败', result)
            } catch(e) {
                console.log(e)
                return new CommonResponseDto(ResCode.ERROR, '服务异常', null)
            }
        } else {
            return new CommonResponseDto(ResCode.ERROR, 'access_token获取失败', null)
        }
    }
}
